import 'package:app/constants/http_constants.dart';
import 'package:app/http/api_service.dart';
import 'package:app/models/response.dart';
import 'package:app/models/user.dart';
import 'package:app/theme/design_tokens.dart';
import 'package:app/widgets/icons/close_icon.dart';
import 'package:app/widgets/message.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:flutter/material.dart';

enum EditInfoPageActionType {
  // 名字
  name,
  // 职务
  position,
  // 企业
  enterprise,
}

class EditInfoPage extends StatefulWidget {
  const EditInfoPage({super.key, this.data, required this.actionType});

  final String? data; // 数据默认值(名字、职务、企业)
  final EditInfoPageActionType actionType; // 编辑类型
  @override
  State<EditInfoPage> createState() => _EditNameRouteState();
}

class _EditNameRouteState extends State<EditInfoPage> {
  final maxLen = 8; // 昵称最大长度
  final TextEditingController _textController =
      TextEditingController(); // 昵称输入框控制器
  int _length = 0;

  @override
  void initState() {
    if (widget.data != null && widget.data != "null") {
      _textController.text = widget.data!;
      _length = _textController.text.length;
    }
    super.initState();
  }

  // 标题
  Widget _buildAppBarTitle() {
    String _title;

    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        _title = "修改姓名";
        break;
      case EditInfoPageActionType.enterprise:
        _title = "修改所在企业";
        break;
      case EditInfoPageActionType.position:
        _title = "修改职务";
        break;
    }

    return Text(_title);
  }

  // 输入框提示文字
  String get _hintText {
    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        return "请输入昵称";
      case EditInfoPageActionType.enterprise:
        return "请输入公司名称";
      case EditInfoPageActionType.position:
        return "请输入职务";
    }
  }

  // 输入框
  Widget _buildInput() {
    List<Widget> inputGroup = [
      Expanded(
          child: TextField(
        controller: _textController,
        autofocus: true,
        decoration: InputDecoration(
          hintText: _hintText,
          contentPadding: const EdgeInsets.symmetric(horizontal: 0),
        ),
        onChanged: (value) {
          _validateOnInput(value);
        },
      )),
      InkWell(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        child: const Padding(
          padding: EdgeInsets.fromLTRB(10, 20, 0, 20),
          child: CloseIconWidget(),
        ),
        onTap: () {
          _textController.clear();
        },
      ),
    ];

    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        inputGroup.addAll([
          const SizedBox(
            width: 10,
          ),
          Text(
            "$_length/$maxLen",
            style: const TextStyle(color: Color(0xFF999999)),
          )
        ]);
        break;
      case EditInfoPageActionType.enterprise:
      case EditInfoPageActionType.position:
        break;
    }
    return Row(
      children: inputGroup,
    );
  }

  // 输入框输入时的校验信息
  void _validateOnInput(String value) {
    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        if (value.length > 8) {
          _textController.text = value.substring(0, maxLen);
          Message.showToast(msg: "昵称不能超过$maxLen个字符");
        }
        setState(() {
          _length = _textController.text.length;
        });
        break;
      case EditInfoPageActionType.enterprise:
      case EditInfoPageActionType.position:
        break;
    }
  }

  // 根据类型写不同的校验方法
  bool _validate() {
    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        if (_textController.text.isEmpty) {
          Message.showToast(msg: "昵称不能为空");
          return false;
        }
        break;
      case EditInfoPageActionType.enterprise:
        if (_textController.text.isEmpty) {
          Message.showToast(msg: "公司名称不能为空");
          return false;
        }
        break;
      case EditInfoPageActionType.position:
        if (_textController.text.isEmpty) {
          Message.showToast(msg: "职务不能为空");
          return false;
        }
        break;
    }
    return true;
  }

  // 校验完成后执行不同的操作
  Future<void> _onCompleted() async {
    // 如果当前信息和输入信息一致，则不做任何操作，直接返回
    if (widget.data == _textController.text) {
      Navigator.pop(context, null);
      return;
    }

    UserInfo user;

    switch (widget.actionType) {
      case EditInfoPageActionType.name:
        user = UserInfo(name: _textController.text);
        break;
      case EditInfoPageActionType.enterprise:
        user = UserInfo(enterprise: _textController.text);
        break;
      case EditInfoPageActionType.position:
        user = UserInfo(position: _textController.text);
        break;
    }

    ResponseData data = await ApiService(context).updateUserInfo(user);
    if (data.code == HttpConstants.SUCCEED_CODE) {
      Message.showToast(msg: "修改成功");
      Navigator.pop(context, _textController.text);
    }
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: true,
        onPopInvokedWithResult: (didPop, result) async {},
        child: Scaffold(
          appBar: AppBar(
            title: _buildAppBarTitle(),
            actions: [
              TextButton(
                onPressed: () async {
                  if (_validate() == false) return;
                  _onCompleted();
                },
                child: const Text("确定"),
              )
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                _buildInput(),
                const SizedBox(
                  height: 14,
                ),
                CreatoDivider()
              ],
            ),
          ),
        ));
  }
}
